package net.shopxx.action.shop;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;

import net.sf.json.JSONArray;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;
import net.shopxx.bean.CartItemCookie;
import net.shopxx.bean.SystemConfig.PointType;
import net.shopxx.entity.CartItem;
import net.shopxx.entity.CartItemGroupbuy;
import net.shopxx.entity.CartItemProduct;
import net.shopxx.entity.Groupbuy;
import net.shopxx.entity.Member;
import net.shopxx.entity.Product;
import net.shopxx.entity.Productitem;
import net.shopxx.service.CartItemService;
import net.shopxx.service.GroupbuyService;
import net.shopxx.service.ProductService;
import net.shopxx.service.ProductitemService;
import net.shopxx.util.SystemConfigUtil;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;

import com.opensymphony.xwork2.interceptor.annotations.InputConfig;
import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
import com.opensymphony.xwork2.validator.annotations.Validations;

/**
 * 前台Action类 - 购物车项
 */

@ParentPackage("shop")
public class CartItemAction extends BaseShopAction {

	private static final long serialVersionUID = 4404250263935012169L;
	private String type;
	private Integer quantity;// 商品数量
	private Integer totalQuantity;// 商品总数
	private Integer totalPoint;// 总积分
	private BigDecimal totalPrice;// 总计商品价格
	private List<CartItem> cartItemList = new ArrayList<CartItem>();
	
	private List<String> productProperties = new ArrayList<String>();

	@Resource
	private ProductService productService;
	@Resource
	private GroupbuyService groupbuyService;
	@Resource
	private CartItemService cartItemService;
	@Resource
	private ProductitemService productitemService;
	
	// 添加购物车项
	@SuppressWarnings("unchecked")
	@Validations(
		requiredStrings = {
			@RequiredStringValidator(fieldName = "id", message = "ID不允许为空!"),
			@RequiredStringValidator(fieldName = "type", message = "type不允许为空!")
		}
	)
	@InputConfig(resultName = "error")
	public String ajaxAdd() {
		BigDecimal totalPrice = new BigDecimal("0");// 总计商品价格
		Integer totalQuantity = 0;// 总计商品数量
		if(type.equalsIgnoreCase(CartItem.TYPE_PRODUCT))
		{
			Productitem productItem = productitemService.load(id);
//			Product product = productService.load(id);
			Product product = productItem.getProduct();
			if (!product.getIsMarketable()) {
				return ajaxJsonErrorMessage("此商品已下架!");
			}
			if (quantity == null || quantity < 1) {
				quantity = 1;
			}
			Member loginMember = getLoginMember();
			if (loginMember == null) {
				List<CartItemCookie> cartItemCookieList = new ArrayList<CartItemCookie>();
				boolean isExist = false;
				Cookie[] cookies = getRequest().getCookies();
				if (cookies != null && cookies.length > 0) {
					for (Cookie cookie : cookies) {
						if (StringUtils.equalsIgnoreCase(cookie.getName(), CartItemCookie.CART_ITEM_LIST_COOKIE_NAME)) {
							if (StringUtils.isNotEmpty(cookie.getValue())) {
								JsonConfig jsonConfig = new JsonConfig();
								jsonConfig.setRootClass(CartItemCookie.class);
								JSONArray jsonArray = JSONArray.fromObject(cookie.getValue());
								List<CartItemCookie> previousCartItemCookieList = (List<CartItemCookie>) JSONSerializer.toJava(jsonArray, jsonConfig);
								for (CartItemCookie previousCartItemCookie : previousCartItemCookieList) {
									
									if(previousCartItemCookie.getT().equals(CartItem.TYPE_PRODUCT))
									{
										Productitem cartItemCookieProductItem = productitemService.load(previousCartItemCookie.getI());
//										Product cartItemCookieProduct = productService.load(previousCartItemCookie.getI());
										Product cartItemCookieProduct = cartItemCookieProductItem.getProduct();
										if (StringUtils.equals(previousCartItemCookie.getI(), id)) {
											isExist = true;
											previousCartItemCookie.setQ(previousCartItemCookie.getQ() + quantity);
											if (isLack(product, previousCartItemCookie.getQ())) {
												return ajaxJsonErrorMessage("添加购物车失败，商品库存不足!");
											}
										}
										cartItemCookieList.add(previousCartItemCookie);
										totalPrice =  cartItemCookieProduct.getPreferentialPrice(getLoginMember()).multiply(new BigDecimal(previousCartItemCookie.getQ().toString())).add(totalPrice);
										totalQuantity += previousCartItemCookie.getQ();
									}
									else
									{
										Groupbuy cartItemObj = groupbuyService.load(previousCartItemCookie.getI());
										cartItemCookieList.add(previousCartItemCookie);
										totalPrice =  cartItemObj.getPreferentialPrice(getLoginMember()).multiply(new BigDecimal(previousCartItemCookie.getQ().toString())).add(totalPrice);
										totalQuantity += previousCartItemCookie.getQ();
									}
								}
							}
						}
					}
				}
				if (!isExist) {
					CartItemCookie cartItemCookie = new CartItemCookie();
					cartItemCookie.setI(id);
					cartItemCookie.setQ(quantity);
					cartItemCookie.setT(CartItem.TYPE_PRODUCT);
					cartItemCookieList.add(cartItemCookie);
					totalQuantity += quantity;
					totalPrice =  product.getPreferentialPrice(getLoginMember()).multiply(new BigDecimal(quantity.toString())).add(totalPrice);
					if (isLack(product, cartItemCookie.getQ())) {
						return ajaxJsonErrorMessage("添加购物车失败，商品库存不足!");
					}
				}
				for (CartItemCookie cartItemCookie : cartItemCookieList) {
					if (StringUtils.equals(cartItemCookie.getI(), id)) {
						Productitem cartItemCookieProductItem = productitemService.load(cartItemCookie.getI());
//						Product cartItemCookieProduct = productService.load(cartItemCookie.getI());
						Product cartItemCookieProduct = cartItemCookieProductItem.getProduct();
						if (product.getStore() != null && (cartItemCookieProduct.getFreezeStore() + cartItemCookie.getQ()) > cartItemCookieProduct.getStore()) {
							return ajaxJsonErrorMessage("添加购物车失败，商品库存不足!");
						}
					}
				}
				JSONArray jsonArray = JSONArray.fromObject(cartItemCookieList);
				Cookie cookie = new Cookie(CartItemCookie.CART_ITEM_LIST_COOKIE_NAME, jsonArray.toString());
				cookie.setPath(getRequest().getContextPath() + "/");
				cookie.setMaxAge(CartItemCookie.CART_ITEM_LIST_COOKIE_MAX_AGE);
				getResponse().addCookie(cookie);
			} else {
				boolean isExist = false;
				Set<CartItem> previousCartItemList = loginMember.getCartItemSet();
				if (previousCartItemList != null) {
					for (CartItem previousCartItemTemp : previousCartItemList) {
						if(previousCartItemTemp instanceof CartItemProduct)
						{
							CartItemProduct previousCartItem= null;
							previousCartItem= (CartItemProduct)previousCartItemTemp;
							if (StringUtils.equals(previousCartItem.getProductitem().getId(), id)) {
								isExist = true;
								previousCartItem.setQuantity(previousCartItem.getQuantity() + quantity);
								if (product.getStore() != null && (product.getFreezeStore() + previousCartItem.getQuantity()) > product.getStore()) {
									return ajaxJsonErrorMessage("添加购物车失败，商品库存不足!");
								}
								cartItemService.update(previousCartItem);
							}
							totalQuantity += previousCartItem.getQuantity();
							totalPrice =  previousCartItem.getProductitem().getProduct().getPreferentialPrice(getLoginMember()).multiply(new BigDecimal(previousCartItem.getQuantity().toString())).add(totalPrice);
						}
						else
						{

							CartItemGroupbuy previousCartItem= null;
							previousCartItem= (CartItemGroupbuy)previousCartItemTemp;
							if (StringUtils.equals(previousCartItem.getGroupbuy().getId(), id)) {
								isExist = true;
								previousCartItem.setQuantity(previousCartItem.getQuantity() + quantity);
								if (product.getStore() != null && (product.getFreezeStore() + previousCartItem.getQuantity()) > product.getStore()) {
									return ajaxJsonErrorMessage("添加购物车失败，商品库存不足!");
								}
								cartItemService.update(previousCartItem);
							}
							totalQuantity += previousCartItem.getQuantity();
							totalPrice =  previousCartItem.getGroupbuy().getPreferentialPrice(getLoginMember()).multiply(new BigDecimal(previousCartItem.getQuantity().toString())).add(totalPrice);
						
						}
					}
				}
				if (!isExist) {
					CartItemProduct cartItem = new CartItemProduct();
					cartItem.setMember(loginMember);
					cartItem.setProductitem(productItem);
					cartItem.setQuantity(quantity);
					if (product.getStore() != null && (product.getFreezeStore() + cartItem.getQuantity()) > product.getStore()) {
						return ajaxJsonErrorMessage("添加购物车失败，商品库存不足!");
					}
					cartItemService.save(cartItem);
					totalQuantity += quantity;
					totalPrice =  product.getPreferentialPrice(getLoginMember()).multiply(new BigDecimal(quantity.toString())).add(totalPrice);
				}
			}
		}
		else if(type.equalsIgnoreCase(CartItem.TYPE_GROUPBUY))
		{
			Groupbuy groupbuy = groupbuyService.load(id);
			if (!groupbuy.getProduct().getIsMarketable()) {
				return ajaxJsonErrorMessage("此商品已下架!");
			}
			if (quantity == null || quantity < 1) {
				quantity = 1;
			}
			Member loginMember = getLoginMember();
			if (loginMember == null) {
				List<CartItemCookie> cartItemCookieList = new ArrayList<CartItemCookie>();
				boolean isExist = false;
				Cookie[] cookies = getRequest().getCookies();
				if (cookies != null && cookies.length > 0) {
					for (Cookie cookie : cookies) {
						if (StringUtils.equalsIgnoreCase(cookie.getName(), CartItemCookie.CART_ITEM_LIST_COOKIE_NAME)) {
							if (StringUtils.isNotEmpty(cookie.getValue())) {
								JsonConfig jsonConfig = new JsonConfig();
								jsonConfig.setRootClass(CartItemCookie.class);
								JSONArray jsonArray = JSONArray.fromObject(cookie.getValue());
								List<CartItemCookie> previousCartItemCookieList = (List<CartItemCookie>) JSONSerializer.toJava(jsonArray, jsonConfig);
								for (CartItemCookie previousCartItemCookie : previousCartItemCookieList) {
									if(previousCartItemCookie.getT().equals("p"))
									{

										Productitem cartItemCookieProductItem = productitemService.load(previousCartItemCookie.getI());
//										Product cartItemCookieProduct = productService.load(previousCartItemCookie.getI());
										Product cartItemCookieProduct = cartItemCookieProductItem.getProduct();
										
										cartItemCookieList.add(previousCartItemCookie);
										totalQuantity += previousCartItemCookie.getQ();
										totalPrice =  cartItemCookieProduct.getPreferentialPrice(getLoginMember()).multiply(new BigDecimal(previousCartItemCookie.getQ().toString())).add(totalPrice);
									}
									else
									{
										Groupbuy cartItemObj = groupbuyService.load(id);
										if (StringUtils.equals(previousCartItemCookie.getI(), id)) {
											isExist = true;
											previousCartItemCookie.setQ(previousCartItemCookie.getQ() + quantity);
											if (isLack(cartItemObj.getProduct(), previousCartItemCookie.getQ())) {
												return ajaxJsonErrorMessage("添加购物车失败，商品库存不足!");
											}
										}
										cartItemCookieList.add(previousCartItemCookie);
										totalQuantity += previousCartItemCookie.getQ();
										totalPrice =  cartItemObj.getPreferentialPrice(getLoginMember()).multiply(new BigDecimal(previousCartItemCookie.getQ().toString())).add(totalPrice);
									}
									
									
									}
							}
						}
					}
				}
				if (!isExist) {
					CartItemCookie cartItemCookie = new CartItemCookie();
					cartItemCookie.setI(id);
					cartItemCookie.setQ(quantity);
					cartItemCookie.setT(CartItem.TYPE_GROUPBUY);
					cartItemCookieList.add(cartItemCookie);
					totalQuantity += quantity;
					totalPrice =  groupbuy.getPreferentialPrice(getLoginMember()).multiply(new BigDecimal(quantity.toString())).add(totalPrice);
					if (isLack(groupbuy.getProduct(), cartItemCookie.getQ())) {
						return ajaxJsonErrorMessage("添加购物车失败，商品库存不足!");
					}
				}
				for (CartItemCookie cartItemCookie : cartItemCookieList) {
					if (StringUtils.equals(cartItemCookie.getI(), id)) {
						Groupbuy cartItemCookieProduct = groupbuyService.load(cartItemCookie.getI());
						if (cartItemCookieProduct.getProduct().getStore() != null && (cartItemCookieProduct.getProduct().getFreezeStore() + cartItemCookie.getQ()) > cartItemCookieProduct.getProduct().getStore()) {
							return ajaxJsonErrorMessage("添加购物车失败，商品库存不足!");
						}
					}
				}
				JSONArray jsonArray = JSONArray.fromObject(cartItemCookieList);
				Cookie cookie = new Cookie(CartItemCookie.CART_ITEM_LIST_COOKIE_NAME, jsonArray.toString());
				cookie.setPath(getRequest().getContextPath() + "/");
				cookie.setMaxAge(CartItemCookie.CART_ITEM_LIST_COOKIE_MAX_AGE);
				getResponse().addCookie(cookie);
			} else {
				boolean isExist = false;
				Set<CartItem> previousCartItemList = loginMember.getCartItemSet();
				if (previousCartItemList != null) {
					for (CartItem previousCartItemTemp : previousCartItemList) {
						if(previousCartItemTemp instanceof CartItemGroupbuy)
						{
							CartItemGroupbuy previousCartItem = (CartItemGroupbuy)previousCartItemTemp;
							if (StringUtils.equals(previousCartItem.getGroupbuy().getId(), id)) {
								isExist = true;
								previousCartItem.setQuantity(previousCartItem.getQuantity() + quantity);
								if (groupbuy.getProduct().getStore() != null && (groupbuy.getProduct().getFreezeStore() + previousCartItem.getQuantity()) > groupbuy.getProduct().getStore()) {
									return ajaxJsonErrorMessage("添加购物车失败，商品库存不足!");
								}
								cartItemService.update(previousCartItem);
							}
							totalQuantity += previousCartItem.getQuantity();
							totalPrice =  previousCartItem.getGroupbuy().getProduct().getPreferentialPrice(getLoginMember()).multiply(new BigDecimal(previousCartItem.getQuantity().toString())).add(totalPrice);

						}
						else
						{
							CartItemProduct previousCartItem= (CartItemProduct)previousCartItemTemp;
							totalQuantity += previousCartItem.getQuantity();
							totalPrice =  previousCartItem.getProductitem().getProduct().getPreferentialPrice(getLoginMember()).multiply(new BigDecimal(previousCartItem.getQuantity().toString())).add(totalPrice);
						}
					}
				}
				if (!isExist) {
					CartItemGroupbuy cartItem = new CartItemGroupbuy();
					cartItem.setMember(loginMember);
					cartItem.setGroupbuy(groupbuy);
					cartItem.setQuantity(quantity);
					if (groupbuy.getProduct().getStore() != null && (groupbuy.getProduct().getFreezeStore() + cartItem.getQuantity()) > groupbuy.getProduct().getStore()) {
						return ajaxJsonErrorMessage("添加购物车失败，商品库存不足!");
					}
					cartItemService.save(cartItem);
					totalQuantity += quantity;
					totalPrice =  groupbuy.getPreferentialPrice(getLoginMember()).multiply(new BigDecimal(quantity.toString())).add(totalPrice);
				}
			}
		}
		totalPrice = SystemConfigUtil.getOrderScaleBigDecimal(totalPrice);
		DecimalFormat decimalFormat = new DecimalFormat(getOrderUnitCurrencyFormat());
		String totalPriceString = decimalFormat.format(totalPrice);
		Map<String, String> jsonMap = new HashMap<String, String>();
		jsonMap.put(STATUS, SUCCESS);
		jsonMap.put(MESSAGE, "添加至购物车成功！");
		jsonMap.put("totalQuantity", totalQuantity.toString());
		jsonMap.put("totalPrice", totalPriceString);
		return ajaxJson(jsonMap);
	}
	
	private boolean checkStore()
	{
		return true;
	}
	
	private boolean checkIsMarketable()
	{
		return true;
	}

	private boolean isLack(Product product,
			Integer quantity) {
		return product.getStore() != null && (product.getFreezeStore() + quantity) > product.getStore();
	}
	
	// 购物车项列表
	@InputConfig(resultName = "error")
	@SuppressWarnings("unchecked")
	public String ajaxList() {
		List<Map<String, String>> jsonList = new ArrayList<Map<String, String>>();
		Member loginMember = getLoginMember();
		totalQuantity = 0;
		totalPrice = new BigDecimal("0");
		if (loginMember == null) {
			Cookie[] cookies = getRequest().getCookies();
			if (cookies != null && cookies.length > 0) {
				for (Cookie cookie : cookies) {
					if (StringUtils.equalsIgnoreCase(cookie.getName(), CartItemCookie.CART_ITEM_LIST_COOKIE_NAME)) {
						if (StringUtils.isNotEmpty(cookie.getValue())) {
							JsonConfig jsonConfig = new JsonConfig();
							jsonConfig.setRootClass(CartItemCookie.class);
							JSONArray jsonArray = JSONArray.fromObject(cookie.getValue());
							List<CartItemCookie> cartItemCookieList = (List<CartItemCookie>) JSONSerializer.toJava(jsonArray, jsonConfig);
							for (CartItemCookie cartItemCookie : cartItemCookieList) {
								if(CartItem.TYPE_PRODUCT.equalsIgnoreCase(cartItemCookie.getT()))
								{
//									Product product = productService.load(cartItemCookie.getI());

									Productitem cartItemCookieProductItem = productitemService.load(cartItemCookie.getI());
									Product product = cartItemCookieProductItem.getProduct();
									
									if (product != null) {
										totalQuantity += cartItemCookie.getQ();
										totalPrice = product.getPreferentialPrice(getLoginMember()).multiply(new BigDecimal(cartItemCookie.getQ().toString())).add(totalPrice);
										DecimalFormat decimalFormat = new DecimalFormat(getPriceCurrencyFormat());
										String priceString = decimalFormat.format(product.getPreferentialPrice(getLoginMember()));
										Map<String, String> jsonMap = new HashMap<String, String>();
										jsonMap.put("name", product.getName());
										jsonMap.put("price", priceString);
										jsonMap.put("quantity", cartItemCookie.getQ().toString());
										jsonMap.put("htmlFilePath", product.getHtmlFilePath());
										jsonList.add(jsonMap);
									}
								}
								else
								{
									Groupbuy product = groupbuyService.load(cartItemCookie.getI());
									if (product != null) {
										totalQuantity += cartItemCookie.getQ();
										totalPrice = product.getPreferentialPrice(getLoginMember()).multiply(new BigDecimal(cartItemCookie.getQ().toString())).add(totalPrice);
										DecimalFormat decimalFormat = new DecimalFormat(getPriceCurrencyFormat());
										String priceString = decimalFormat.format(product.getPreferentialPrice(getLoginMember()));
										Map<String, String> jsonMap = new HashMap<String, String>();
										jsonMap.put("name", product.getName());
										jsonMap.put("price", priceString);
										jsonMap.put("quantity", cartItemCookie.getQ().toString());
										jsonMap.put("htmlFilePath", product.getHtmlFilePath());
										jsonList.add(jsonMap);
									}
								}
							}
						}
					}
				}
			}
		} else {
			Set<CartItem> cartItemSet = loginMember.getCartItemSet();
			if (cartItemSet != null) {
				for (CartItem cartItemTemp : cartItemSet) {
					if(cartItemTemp instanceof CartItemProduct)
					{
						CartItemProduct cartItem = (CartItemProduct)cartItemTemp;
						Product product = cartItem.getProductitem().getProduct();
						totalQuantity += cartItem.getQuantity();
						totalPrice = product.getPreferentialPrice(getLoginMember()).multiply(new BigDecimal(cartItem.getQuantity().toString())).add(totalPrice);
						DecimalFormat decimalFormat = new DecimalFormat(getPriceCurrencyFormat());
						String priceString = decimalFormat.format(product.getPreferentialPrice(getLoginMember()));
						Map<String, String> jsonMap = new HashMap<String, String>();
						jsonMap.put("name", product.getName());
						jsonMap.put("price", priceString);
						jsonMap.put("quantity", cartItem.getQuantity().toString());
						jsonMap.put("htmlFilePath", product.getHtmlFilePath());
						jsonList.add(jsonMap);
					}
					else if(cartItemTemp instanceof CartItemGroupbuy)
					{
						CartItemGroupbuy cartItem = (CartItemGroupbuy)cartItemTemp;
						Groupbuy groupbuy = cartItem.getGroupbuy();
						totalQuantity += cartItem.getQuantity();
						totalPrice = groupbuy.getPreferentialPrice(getLoginMember()).multiply(new BigDecimal(cartItem.getQuantity().toString())).add(totalPrice);
						DecimalFormat decimalFormat = new DecimalFormat(getPriceCurrencyFormat());
						String priceString = decimalFormat.format(cartItem.getGroupbuy().getPreferentialPrice(getLoginMember()));
						Map<String, String> jsonMap = new HashMap<String, String>();
						jsonMap.put("name", groupbuy.getName());
						jsonMap.put("price", priceString);
						jsonMap.put("quantity", cartItem.getQuantity().toString());
						jsonMap.put("htmlFilePath", cartItem.getGroupbuy().getHtmlFilePath());
						jsonList.add(jsonMap);
					}
				}
			}
		}
		totalPrice = SystemConfigUtil.getOrderScaleBigDecimal(totalPrice);
		DecimalFormat decimalFormat = new DecimalFormat(getOrderUnitCurrencyFormat());
		String totalPriceString = decimalFormat.format(totalPrice);
		Map<String, String> jsonMap = new HashMap<String, String>();
		jsonMap.put("totalQuantity", totalQuantity.toString());
		jsonMap.put("totalPrice", totalPriceString);
		jsonList.add(0, jsonMap);
		JSONArray jsonArray = JSONArray.fromObject(jsonList);
		return ajaxJson(jsonArray.toString());
	}
	
	// 购物车项列表
	@SuppressWarnings("unchecked")
	@InputConfig(resultName = "error")
	public String list() {
		Member loginMember = getLoginMember();
		totalQuantity = 0;
		totalPoint = 0;
		totalPrice = new BigDecimal("0");
		if (loginMember == null) {
			Cookie[] cookies = getRequest().getCookies();
			if (cookies != null && cookies.length > 0) {
				for (Cookie cookie : cookies) {
					if (StringUtils.equalsIgnoreCase(cookie.getName(), CartItemCookie.CART_ITEM_LIST_COOKIE_NAME)) {
						if (StringUtils.isNotEmpty(cookie.getValue())) {
							JsonConfig jsonConfig = new JsonConfig();
							jsonConfig.setRootClass(CartItemCookie.class);
							JSONArray jsonArray = JSONArray.fromObject(cookie.getValue());
							List<CartItemCookie> cartItemCookieList = (List<CartItemCookie>) JSONSerializer.toJava(jsonArray, jsonConfig);
							for (CartItemCookie cartItemCookie : cartItemCookieList) {
								if(CartItem.TYPE_PRODUCT.equalsIgnoreCase(cartItemCookie.getT()))
								{
//									Product product = productService.load(cartItemCookie.getI());
									

									Productitem cartItemCookieProductItem = productitemService.load(cartItemCookie.getI());
									Product product = cartItemCookieProductItem.getProduct();
									
									if (product != null) {
										totalQuantity += cartItemCookie.getQ();
										if (getSystemConfig().getPointType() == PointType.productSet) {
											totalPoint = product.getPoint() * cartItemCookie.getQ() + totalPoint;
										}
										totalPrice = product.getPreferentialPrice(getLoginMember()).multiply(new BigDecimal(cartItemCookie.getQ().toString())).add(totalPrice);
										CartItemProduct cartItem = new CartItemProduct();
										cartItem.setProductitem(cartItemCookieProductItem);
										cartItem.setQuantity(cartItemCookie.getQ());
										cartItemList.add(cartItem);
									}
								}
								else if(cartItemCookie.getT().equalsIgnoreCase(CartItem.TYPE_GROUPBUY))
								{
									Groupbuy groupbuy = groupbuyService.load(cartItemCookie.getI());
									if (groupbuy != null) {
										totalQuantity += cartItemCookie.getQ();
										if (getSystemConfig().getPointType() == PointType.productSet) {
											totalPoint = groupbuy.getProduct().getPoint() * cartItemCookie.getQ() + totalPoint;
										}
										totalPrice = groupbuy.getPreferentialPrice(getLoginMember()).multiply(new BigDecimal(cartItemCookie.getQ().toString())).add(totalPrice);
										CartItemGroupbuy cartItem = new CartItemGroupbuy();
										cartItem.setGroupbuy(groupbuy);
										cartItem.setQuantity(cartItemCookie.getQ());
										cartItemList.add(cartItem);
									}
									
								}
								
							}
						}
					}
				}
			}
		} else {
			Set<CartItem> cartItemSet = loginMember.getCartItemSet();
			if (cartItemSet != null) {
				cartItemList = new ArrayList<CartItem>(cartItemSet);
				for (CartItem cartItemTemp : cartItemSet) {
					if (cartItemTemp instanceof CartItemProduct) {
						CartItemProduct cartItem = (CartItemProduct) cartItemTemp;
						totalQuantity += cartItem.getQuantity();
						if (getSystemConfig().getPointType() == PointType.productSet) {
							totalPoint = cartItem.getProductitem().getProduct().getPoint() * cartItem.getQuantity() + totalPoint;
						}
						totalPrice = cartItem.getProductitem().getProduct().getPreferentialPrice(getLoginMember()).multiply(new BigDecimal(cartItem.getQuantity().toString())).add(totalPrice);
					}
					else if(cartItemTemp instanceof CartItemGroupbuy) {
						CartItemGroupbuy cartItem = (CartItemGroupbuy) cartItemTemp;
						totalQuantity += cartItem.getQuantity();
						if (getSystemConfig().getPointType() == PointType.productSet) {
							totalPoint = cartItem.getGroupbuy().getProduct().getPoint() * cartItem.getQuantity() + totalPoint;
						}
						totalPrice = cartItem.getGroupbuy().getPreferentialPrice(getLoginMember()).multiply(new BigDecimal(cartItem.getQuantity().toString())).add(totalPrice);
					}
				}
			}
		}
		totalPrice = SystemConfigUtil.getOrderScaleBigDecimal(totalPrice);
		if (getSystemConfig().getPointType() == PointType.orderAmount) {
			totalPoint = totalPrice.multiply(new BigDecimal(getSystemConfig().getPointScale().toString())).setScale(0, RoundingMode.DOWN).intValue();
		}
		setResponseNoCache();
		return "list";
	}
	
	// 修改购物车项
	@InputConfig(resultName = "error")
	@SuppressWarnings("unchecked")
	public String ajaxEdit() {
		if (quantity == null || quantity < 1) {
			quantity = 1;
		}
		Member loginMember = getLoginMember();
		totalQuantity = 0;
		totalPoint = 0;
		totalPrice = new BigDecimal("0");
		BigDecimal subtotalPrice = new BigDecimal("0");
		if (loginMember == null) {
			Cookie[] cookies = getRequest().getCookies();
			if (cookies != null && cookies.length > 0) {
				for (Cookie cookie : cookies) {
					if (StringUtils.equalsIgnoreCase(cookie.getName(), CartItemCookie.CART_ITEM_LIST_COOKIE_NAME)) {
						if (StringUtils.isNotEmpty(cookie.getValue())) {
							JsonConfig jsonConfig = new JsonConfig();
							jsonConfig.setRootClass(CartItemCookie.class);
							JSONArray previousJsonArray = JSONArray.fromObject(cookie.getValue());
							List<CartItemCookie> cartItemCookieList = (List<CartItemCookie>) JSONSerializer.toJava(previousJsonArray, jsonConfig);
							Iterator<CartItemCookie> iterator = cartItemCookieList.iterator();
							while (iterator.hasNext()) {
								CartItemCookie cartItemCookie = iterator.next();
								if(cartItemCookie.getT().equalsIgnoreCase(CartItem.TYPE_PRODUCT))
								{
//									Product product = productService.load(cartItemCookie.getI());

									Productitem cartItemCookieProductItem = productitemService.load(cartItemCookie.getI());
									Product product = cartItemCookieProductItem.getProduct();
									
									if (StringUtils.equals(id, cartItemCookie.getI())) {
										cartItemCookie.setQ(quantity);
										subtotalPrice = product.getPreferentialPrice(getLoginMember()).multiply(new BigDecimal(quantity.toString()));
										if (isLack(product, cartItemCookie.getQ())) {
											return ajaxJsonErrorMessage("商品库存不足！");
										}
									}
									totalQuantity += cartItemCookie.getQ();
									if (getSystemConfig().getPointType() == PointType.productSet) {
										totalPoint = product.getPoint() * cartItemCookie.getQ() + totalPoint;
									}
									totalPrice = product.getPreferentialPrice(getLoginMember()).multiply(new BigDecimal(cartItemCookie.getQ().toString())).add(totalPrice);
									
								}
								else if(cartItemCookie.getT().equalsIgnoreCase(CartItem.TYPE_GROUPBUY))
								{
									Groupbuy groupbuy = groupbuyService.load(cartItemCookie.getI());
									if (StringUtils.equals(id, cartItemCookie.getI())) {
										cartItemCookie.setQ(quantity);
										subtotalPrice = groupbuy.getPreferentialPrice(getLoginMember()).multiply(new BigDecimal(quantity.toString()));
										if (groupbuy.getProduct().getStore() != null && (groupbuy.getProduct().getFreezeStore() + cartItemCookie.getQ()) > groupbuy.getProduct().getStore()) {
											return ajaxJsonErrorMessage("商品库存不足！");
										}
									}
									totalQuantity += cartItemCookie.getQ();
									if (getSystemConfig().getPointType() == PointType.productSet) {
										totalPoint = groupbuy.getProduct().getPoint() * cartItemCookie.getQ() + totalPoint;
									}
									totalPrice = groupbuy.getPreferentialPrice(getLoginMember()).multiply(new BigDecimal(cartItemCookie.getQ().toString())).add(totalPrice);
								}
							}
							JSONArray jsonArray = JSONArray.fromObject(cartItemCookieList);
							Cookie newCookie = new Cookie(CartItemCookie.CART_ITEM_LIST_COOKIE_NAME, jsonArray.toString());
							newCookie.setPath(getRequest().getContextPath() + "/");
							newCookie.setMaxAge(CartItemCookie.CART_ITEM_LIST_COOKIE_MAX_AGE);
							getResponse().addCookie(newCookie);
						}
					}
				}
			}
		} else {
			Set<CartItem> cartItemSet = loginMember.getCartItemSet();
			if (cartItemSet != null) {
				for (CartItem cartItemTemp : cartItemSet) {
					if (cartItemTemp instanceof CartItemProduct) {
						CartItemProduct cartItem = (CartItemProduct) cartItemTemp;
						Productitem productitem = cartItem.getProductitem();
						Product product = productitem.getProduct();
						if (StringUtils.equals(id, productitem.getId())) {
							cartItem.setQuantity(quantity);
							if (product.getStore() != null && (product.getFreezeStore() + cartItem.getQuantity()) > product.getStore()) {
								return ajaxJsonErrorMessage("商品库存不足！");
							}
							cartItemService.update(cartItem);
							subtotalPrice = cartItem.getSubtotalPrice();
						}
						totalQuantity += cartItem.getQuantity();
						if (getSystemConfig().getPointType() == PointType.productSet) {
							totalPoint = product.getPoint() * cartItem.getQuantity() + totalPoint;
						}
						totalPrice = product.getPreferentialPrice(getLoginMember()).multiply(new BigDecimal(cartItem.getQuantity().toString())).add(totalPrice);						
					}
					else if(cartItemTemp instanceof CartItemGroupbuy) {
						CartItemGroupbuy cartItem = (CartItemGroupbuy) cartItemTemp;
						Groupbuy groupbuy = cartItem.getGroupbuy();
						if (StringUtils.equals(id, cartItem.getGroupbuy().getId())) {
							cartItem.setQuantity(quantity);
							if (groupbuy.getProduct().getStore() != null && (groupbuy.getProduct().getFreezeStore() + cartItem.getQuantity()) > groupbuy.getProduct().getStore()) {
								return ajaxJsonErrorMessage("商品库存不足！");
							}
							cartItemService.update(cartItem);
							subtotalPrice = cartItem.getSubtotalPrice();
						}
						totalQuantity += cartItem.getQuantity();
						if (getSystemConfig().getPointType() == PointType.productSet) {
							totalPoint = groupbuy.getProduct().getPoint() * cartItem.getQuantity() + totalPoint;
						}
						totalPrice = groupbuy.getPreferentialPrice(getLoginMember()).multiply(new BigDecimal(cartItem.getQuantity().toString())).add(totalPrice);
					}
					
					
					
					
					
				}
			}
		}
		DecimalFormat orderUnitCurrencyFormat = new DecimalFormat(getOrderUnitCurrencyFormat());
		DecimalFormat orderCurrencyFormat = new DecimalFormat(getOrderCurrencyFormat());
		totalPrice = SystemConfigUtil.getOrderScaleBigDecimal(totalPrice);
		if (getSystemConfig().getPointType() == PointType.orderAmount) {
			totalPoint = totalPrice.multiply(new BigDecimal(getSystemConfig().getPointScale().toString())).setScale(0, RoundingMode.DOWN).intValue();
		}
		String subtotalPriceString = orderCurrencyFormat.format(subtotalPrice);
		String totalPriceString = orderUnitCurrencyFormat.format(totalPrice);
		Map<String, String> jsonMap = new HashMap<String, String>();
		jsonMap.put("subtotalPrice", subtotalPriceString);
		jsonMap.put("totalQuantity", totalQuantity.toString());
		jsonMap.put("totalPoint", totalPoint.toString());
		jsonMap.put("totalPrice", totalPriceString);
		jsonMap.put(STATUS, SUCCESS);
		return ajaxJson(jsonMap);
	}
	
	// 删除购物车项
	@InputConfig(resultName = "error")
	@SuppressWarnings("unchecked")
	public String ajaxDelete() {
		Member loginMember = getLoginMember();
		totalQuantity = 0;
		totalPoint = 0;
		totalPrice = new BigDecimal("0");
		if (loginMember == null) {
			Cookie[] cookies = getRequest().getCookies();
			if (cookies != null && cookies.length > 0) {
				for (Cookie cookie : cookies) {
					if (StringUtils.equalsIgnoreCase(cookie.getName(), CartItemCookie.CART_ITEM_LIST_COOKIE_NAME)) {
						if (StringUtils.isNotEmpty(cookie.getValue())) {
							JsonConfig jsonConfig = new JsonConfig();
							jsonConfig.setRootClass(CartItemCookie.class);
							JSONArray previousJsonArray = JSONArray.fromObject(cookie.getValue());
							List<CartItemCookie> cartItemCookieList = (List<CartItemCookie>) JSONSerializer.toJava(previousJsonArray, jsonConfig);
							Iterator<CartItemCookie> iterator = cartItemCookieList.iterator();
							while (iterator.hasNext()) {
								CartItemCookie cartItemCookie = iterator.next();
								if (StringUtils.equals(cartItemCookie.getI(), id)) {
									iterator.remove();
								} else {
//									Product product = productService.load(cartItemCookie.getI());
									
									Productitem cartItemCookieProductItem = productitemService.load(cartItemCookie.getI());
									Product product = cartItemCookieProductItem.getProduct();
									
									totalQuantity += cartItemCookie.getQ();
									if (getSystemConfig().getPointType() == PointType.productSet) {
										totalPoint = product.getPoint() * cartItemCookie.getQ() + totalPoint;
									}
									totalPrice = product.getPreferentialPrice(getLoginMember()).multiply(new BigDecimal(cartItemCookie.getQ().toString())).add(totalPrice);
								}
							}
							JSONArray jsonArray = JSONArray.fromObject(cartItemCookieList);
							Cookie newCookie = new Cookie(CartItemCookie.CART_ITEM_LIST_COOKIE_NAME, jsonArray.toString());
							newCookie.setPath(getRequest().getContextPath() + "/");
							newCookie.setMaxAge(CartItemCookie.CART_ITEM_LIST_COOKIE_MAX_AGE);
							getResponse().addCookie(newCookie);
						}
					}
				}
			}
		} else {
			Set<CartItem> cartItemSet = loginMember.getCartItemSet();
			if (cartItemSet != null) {
				for (CartItem cartItemTemp : cartItemSet) {
					if (cartItemTemp instanceof CartItemProduct) {
						CartItemProduct cartItem = (CartItemProduct) cartItemTemp;
						if (StringUtils.equals(cartItem.getProductitem().getId(), id)) {
							cartItemService.delete(cartItem);
						} else {
							Productitem productitem = cartItem.getProductitem();
							Product product = productitem.getProduct();
							totalQuantity += cartItem.getQuantity();
							if (getSystemConfig().getPointType() == PointType.productSet) {
								totalPoint = product.getPoint() * cartItem.getQuantity() + totalPoint;
							}
							totalPrice = product.getPreferentialPrice(getLoginMember()).multiply(new BigDecimal(cartItem.getQuantity().toString())).add(totalPrice);
						}
					}
					else if (cartItemTemp instanceof CartItemGroupbuy) {
						CartItemGroupbuy cartItem = (CartItemGroupbuy) cartItemTemp;
						if (StringUtils.equals(cartItem.getGroupbuy().getId(), id)) {
							cartItemService.delete(cartItem);
						} else {
							Groupbuy groupbuy = cartItem.getGroupbuy();
							totalQuantity += cartItem.getQuantity();
							if (getSystemConfig().getPointType() == PointType.productSet) {
								totalPoint = groupbuy.getProduct().getPoint() * cartItem.getQuantity() + totalPoint;
							}
							totalPrice = groupbuy.getPreferentialPrice(getLoginMember()).multiply(new BigDecimal(cartItem.getQuantity().toString())).add(totalPrice);
						}
					}
					
					
				}
			}
		}
		totalPrice = SystemConfigUtil.getOrderScaleBigDecimal(totalPrice);
		if (getSystemConfig().getPointType() == PointType.orderAmount) {
			totalPoint = totalPrice.multiply(new BigDecimal(getSystemConfig().getPointScale().toString())).setScale(0, RoundingMode.DOWN).intValue();
		}
		DecimalFormat decimalFormat = new DecimalFormat(getOrderUnitCurrencyFormat());
		String totalPriceString = decimalFormat.format(totalPrice);
		Map<String, String> jsonMap = new HashMap<String, String>();
		jsonMap.put("totalQuantity", totalQuantity.toString());
		jsonMap.put("totalPoint", totalPoint.toString());
		jsonMap.put("totalPrice", totalPriceString);
		jsonMap.put(STATUS, SUCCESS);
		jsonMap.put(MESSAGE, "商品删除成功！");
		return ajaxJson(jsonMap);
	}
	
	// 清空购物车项
	@InputConfig(resultName = "error")
	@SuppressWarnings("unchecked")
	public String ajaxClear() {
		Member loginMember = getLoginMember();
		if (loginMember == null) {
			Cookie cookie = new Cookie(CartItemCookie.CART_ITEM_LIST_COOKIE_NAME, null);
			cookie.setPath(getRequest().getContextPath() + "/");
			cookie.setMaxAge(0);
			getResponse().addCookie(cookie);
		} else {
			Set<CartItem> cartItemSet = loginMember.getCartItemSet();
			if (cartItemSet != null) {
				for (CartItem cartItem : cartItemSet) {
					cartItemService.delete(cartItem);
				}
			}
		}
		return ajaxJsonSuccessMessage("购物车清空成功！");
	}
	
	public Integer getQuantity() {
		return quantity;
	}

	public void setQuantity(Integer quantity) {
		this.quantity = quantity;
	}

	public Integer getTotalQuantity() {
		return totalQuantity;
	}

	public void setTotalQuantity(Integer totalQuantity) {
		this.totalQuantity = totalQuantity;
	}
	
	public Integer getTotalPoint() {
		return totalPoint;
	}

	public void setTotalPoint(Integer totalPoint) {
		this.totalPoint = totalPoint;
	}

	public BigDecimal getTotalPrice() {
		return totalPrice;
	}

	public void setTotalPrice(BigDecimal totalPrice) {
		this.totalPrice = totalPrice;
	}

	public List<CartItem> getCartItemList() {
		return cartItemList;
	}

	public void setCartItemList(List<CartItem> cartItemList) {
		this.cartItemList = cartItemList;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public List<String> getProductProperties() {
		return productProperties;
	}

	public void setProductProperties(List<String> productProperties) {
		this.productProperties = productProperties;
	}
	
	
	

}